<template>
  <div class="admin-profile">
    <el-card class="profile-card">
      <div slot="header" class="clearfix">
        <span class="card-title">个人信息</span>
      </div>
      
      <div class="profile-content">
        <!-- 个人信息展示与编辑 -->
        <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px" v-loading="loading">
          <!-- 头像上传 -->
          <div class="avatar-container">
            <el-avatar :size="100" :src="userForm.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"></el-avatar>
            <el-button type="text" class="avatar-upload-btn" @click="showAvatarUpload = true">
              <i class="el-icon-edit"></i> 修改头像
            </el-button>
          </div>

          <!-- 基本信息 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" disabled></el-input>
          </el-form-item>
          
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="userForm.realName" :disabled="!isEditing"></el-input>
          </el-form-item>
          
          <!-- <el-form-item label="手机号码" prop="phone">
            <el-input v-model="userForm.phone" :disabled="!isEditing"></el-input>
          </el-form-item> -->
          
          <!-- <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="userForm.email" :disabled="!isEditing"></el-input>
          </el-form-item>
          
          <el-form-item label="角色">
            <el-tag :type="roleTypeMap[userForm.role]">{{ roleTextMap[userForm.role] }}</el-tag>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-tag :type="userForm.status === 1 ? 'success' : 'danger'">
              {{ userForm.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-form-item>
          
          <el-form-item label="上次登录">
            <span>{{ userForm.lastLoginTime || '暂无登录记录' }}</span>
          </el-form-item>
          
          <el-form-item label="创建时间">
            <span>{{ userForm.createTime || '未知' }}</span>
          </el-form-item> -->
          
          <el-form-item v-if="isEditing">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </el-form-item>
          <el-form-item v-else>
            <el-button type="primary" @click="startEdit">编辑信息</el-button>
            <el-button type="warning" @click="showPasswordDialog">修改密码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPassword">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog title="上传头像" :visible.sync="showAvatarUpload" width="400px">
      <el-upload
        class="avatar-uploader"
        :action="`${$baseURL}/api/upload/common`"
        :data="{ userId: userForm.id }"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="avatarUrl" :src="avatarUrl" class="avatar-preview">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAvatarUpload = false">取 消</el-button>
        <el-button type="primary" @click="showAvatarUpload = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo, updateUserInfo, changePassword } from '@/api/user'

export default {
  name: 'AdminProfile',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      // 用户信息
      userForm: {
        id: null,
        username: '',
        realName: '',
        phone: '',
        email: '',
        role: null,
        status: null,
        avatar: '',
        lastLoginTime: '',
        createTime: '',
        updateTime: ''
      },
      // 原始用户信息（用于取消编辑时恢复）
      originalUserInfo: null,
      // 是否处于编辑状态
      isEditing: false,
      // 加载状态
      loading: false,
      // 密码表单
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 密码对话框显示状态
      passwordDialogVisible: false,
      // 头像上传对话框显示状态
      showAvatarUpload: false,
      // 新头像URL
      avatarUrl: '',
      // 角色映射
      roleTextMap: {
        1: '学生用户',
        2: '商家用户',
        3: '管理员'
      },
      roleTypeMap: {
        1: 'info',
        2: 'warning',
        3: 'danger'
      },
      // 表单验证规则
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的电子邮箱', trigger: 'blur' }
        ]
      },
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 加载用户信息
    this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      this.loading = true
      // 从本地存储获取用户ID
      const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}')
      const userId = userInfo.id
      
      if (!userId) {
        this.$message.error('未找到用户信息，请重新登录')
        this.$router.push('/login')
        return
      }
      
      getUserInfo(userId).then(response => {
        if (response.code == 200 && response.data) {
          const data = response.data
          this.userForm = data
          // 保存原始用户信息（用于取消编辑）
          this.originalUserInfo = JSON.parse(JSON.stringify(data))
          this.avatarUrl = data.avatar
        } else {
          this.$message.error('获取用户信息失败')
        }
      }).catch(error => {
        console.error('获取用户信息失败', error)
        this.$message.error('获取用户信息失败')
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 开始编辑
    startEdit() {
      this.isEditing = true
    },
    
    // 取消编辑
    cancelEdit() {
      this.isEditing = false
      // 恢复原始用户信息
      if (this.originalUserInfo) {
        this.userForm = JSON.parse(JSON.stringify(this.originalUserInfo))
      }
      // 重置表单验证
      this.$refs.userForm.clearValidate()
    },
    
    // 提交表单
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateUserInfo(this.userForm).then(response => {
            if (response.code == 200) {
              this.$message.success('更新个人信息成功')
              this.isEditing = false
              // 更新原始用户信息
              this.originalUserInfo = JSON.parse(JSON.stringify(this.userForm))
              // 更新本地存储的用户信息
              const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}')
              userInfo.realName = this.userForm.realName
              userInfo.phone = this.userForm.phone
              userInfo.email = this.userForm.email
              userInfo.avatar = this.userForm.avatar
              sessionStorage.setItem('user', JSON.stringify(userInfo))  
            } else {
              this.$message.error(response.message || '更新个人信息失败')
            }
          }).catch(error => {
            console.error('更新个人信息失败', error)
            this.$message.error('更新个人信息失败')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    
    // 显示修改密码对话框
    showPasswordDialog() {    
      this.passwordDialogVisible = true
      // 重置密码表单
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.resetFields()
      }
    },
    
    // 提交修改密码
    submitPassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          const passwordData = {
            userId: this.userForm.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          }
          
          changePassword(passwordData).then(response => {
            if (response.code == 200) {
              this.$message.success('修改密码成功，请重新登录')
              this.passwordDialogVisible = false
              // 退出登录，重新登录
              this.$store.commit('LOGOUT')
              this.$router.push('/login')
            } else {
              this.$message.error(response.message || '修改密码失败')
            }
          }).catch(error => {
            console.error('修改密码失败', error)
            this.$message.error('修改密码失败，请检查原密码是否正确')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    
    // 头像上传成功回调
    handleAvatarSuccess(response, file) {
      if (response.code == 200) {
        this.avatarUrl = URL.createObjectURL(file.raw)
        this.userForm.avatar = response.data.fileUrl
        this.$message.success('头像上传成功')
        
        // 更新本地存储中的用户头像
        const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}')
        userInfo.avatar = response.data.fileUrl
        sessionStorage.setItem('user', JSON.stringify(userInfo))
      } else {
        this.$message.error(response.message || '头像上传失败')
      }
    },
    
    // 头像上传前验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
.admin-profile {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.profile-content {
  padding: 20px 0;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar-upload-btn {
  margin-top: 10px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.avatar-preview {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}
</style> 